package com.lugea.esdemo.configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.http.HttpHost;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author enluw
 * @data 2019/5/21
 */
@Configuration
@ConditionalOnProperty(prefix = "elasticsearch.client", name = "host")
public class EsConfig {
    @Bean
    public TransportClient transportClient(EsClientProperties esClientProperties) throws UnknownHostException {
        Settings settins = Settings.builder().put("cluster.name", esClientProperties.getClusterName()).build();
        PreBuiltTransportClient preBuiltTransportClient = new PreBuiltTransportClient(settins);
        TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(esClientProperties.getHost()),
                esClientProperties.getTcpport());
        preBuiltTransportClient.addTransportAddress(transportAddress);
        return preBuiltTransportClient;
    }

    @Bean
    public RestHighLevelClient restHighLevelClient(EsClientProperties esClientProperties) {
        Node node = new Node(new HttpHost(esClientProperties.getHost(), esClientProperties.getRestport()));
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(node));
        return restHighLevelClient;
    }
}
